package com.szqhyxj.youxiangju.biz.card.credit;

import com.szqhyxj.youxiangju.biz.card.CardModel;
import com.szqhyxj.youxiangju.sys.BaseResult;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * XiaoPanYu
 * on 2018/10/31
 */
public class CreditPresenter implements CreditContarct.Presenter {

    private CreditContarct.View view;
    private List<Disposable> disposables = new ArrayList<>();

    public CreditPresenter(CreditContarct.View view) {
        this.view = view;

        init();
    }

    @Override
    public void init() {
        disposables.add(CardModel.getCards()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(
                        new Consumer<BaseResult<List<CardModel.Card>>>() {
                            @Override
                            public void accept(BaseResult<List<CardModel.Card>> listBaseResult) throws Exception {
                                if (listBaseResult.businessLogicSuccess()&&listBaseResult.getData().size()>0) {
                                    setCards(listBaseResult.getData());
                                } else {
                                    view.showNoCard();
                                }
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                view.showToast(throwable.getMessage());
                                view.showNoCard();
                            }

                        }));

    }

    @Override
    public void setCards(List<CardModel.Card> card) {
        view.showCards(card);
    }

    @Override
    public void onDestroy() {
        for (Disposable disposable : disposables) {
            if (disposable != null) {
                disposable.dispose();
            }
        }
    }
}
